package com.heima.article.interceptor;

import com.heima.utils.thread.WeMediaThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取userId
        String userId = request.getHeader("userId");
        if(!StringUtils.isEmpty(userId)){
            //存入ThreadLocal
            WeMediaThreadLocalUtil.set(Integer.valueOf(userId));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理数据（不清理会导致内存溢出）
        WeMediaThreadLocalUtil.clear();
    }
}
